//
//  ProductDetailViewController.m
//  MyNewProject
//
//  Created by ZhangYuan on 2019/1/28.
//  Copyright © 2019年 sun. All rights reserved.
//
#import "HandInPaymentVC.h"
#import "ProductDetailViewController.h"
#import "YXLPriceHistoryViewController.h"
#import "SDCycleScrollView.h"
#import "ProductInfomationViewCell.h"
#import "ProductAuctionerViewCell.h"
#import "ProductParmsTableViewCell.h"
#import "ProductImagesTableViewCell.h"
#import "XMAlertView.h"
#import "ProductOfferRecordViewController.h"
#import "XMRechargeViewController.h"
#import "QrChargeVC.h"
#import "XM_AuctionProductModel.h"
#import "LoginViewController.h"

#import "XMJSWebViewController.h"

@interface ProductDetailViewController ()<UITableViewDelegate,UITableViewDataSource>{
    XM_AuctionProductDetailModel * productModel;
    XM_JiFenModel * jifenModel;
    CGFloat webCellHeight;
    
    ProductInfomationViewCell * productCell;
}
@property(nonatomic , strong)NSTimer * timer;
@property(nonatomic , retain)UITableView * tableList;
@property(nonatomic , retain)SDCycleScrollView * bannerView;
@property(nonatomic , strong)UIImageView * zhanWeiImageView;

@property(nonatomic , retain)NSMutableArray * tipsArray;
@property(nonatomic , retain)NSMutableArray * contentArray;

@property(nonatomic , retain)UIButton * toSaleSquare;//去卖场
@end

@implementation ProductDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.type = self.type == 0?1:self.type;
    
    self.view.backgroundColor = BackColor;
    self.gk_navigationBar.hidden = NO;
    self.gk_navTitle = @"商品详情";
    [self.view addSubview:self.tableList];
    if (!self.fromOrder) {//订单 没有下面的按钮
        [self.view addSubview:self.toSaleSquare];
    }
    self.tableList.tableHeaderView = self.zhanWeiImageView;

    //请求数据
//    [self requestData];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
}
#pragma - mark 网络请求
-(void)requestData{
    [YQNetworking postWithUrl:self.type == 5?@"Jifen/getJifenInfo":@"index/getSellInfo" refreshRequest:YES cache:NO params:self.type == 5?@{@"id":self.productId}:@{@"sell_id":self.productId} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {

    } successBlock:^(id response) {
        NSMutableArray * imageUrlArray = [NSMutableArray arrayWithArray:@[]];
        for (NSDictionary * dic in response[@"data"][@"lunbo"]) {
            [imageUrlArray addObject:dic[@"imgurl"]];
        }
        if ([imageUrlArray count]>0) {
            self.bannerView.imageURLStringsGroup = imageUrlArray;
            self.tableList.tableHeaderView = self.bannerView;
        }
        if (self.type == 5) {
            self->jifenModel = [XM_JiFenModel modelWithDictionary:response[@"data"][@"goods"]];
            self.contentArray = [NSMutableArray arrayWithArray:@[
            SafeString(self->jifenModel.supplier),[SafeString(self->jifenModel.category) isEqualToString:@""]?@"0":SafeString(self->jifenModel.category),
            SafeString(self->jifenModel.spec),
            [NSString stringWithFormat:@"￥%@",self->jifenModel.refer_price]]];
        }else{
            self->productModel = [XM_AuctionProductDetailModel modelWithDictionary:response[@"data"][@"sell_info"]];
            self->productModel.sell_log = response[@"data"][@"sell_log"];
            self.contentArray = [NSMutableArray arrayWithArray:@[SafeString(self->productModel.begin_time),SafeString(self->productModel.end_time),[NSString stringWithFormat:@"￥%@",self->productModel.refer_price],@"",@""]];
        }
        
        [self.tableList reloadData];
        [self timer];
    } failBlock:^(NSError *error) {

    }];
}
-(void)toSaleSquarePress{//去竞拍
    if ([SafeString([UserInfoSingleton shareInstance].userInfo.loginKey) isEqualToString:@""]) {
        LoginViewController * loginView = [[LoginViewController alloc]init];
        loginView.myLoginResult = ^(id model) {

        };
        [self.navigationController pushViewController:loginView animated:YES];
        return;
    }
    if (self.type == 5) {//积分兑换
        HandInPaymentVC * poVC = [[HandInPaymentVC alloc]init];
        poVC.type = PayTypeScore;
        poVC.idStr = jifenModel.productId;
        [self.navigationController pushViewController:poVC animated:YES];
    }else{
        
        //先判断 账户是否有余额
        if ([[UserInfoSingleton shareInstance].userInfo.yue longLongValue] > 0) {
            YXLPriceHistoryViewController * poVC = [[YXLPriceHistoryViewController alloc]init];
            poVC.sell_id = self.productId;
            poVC.sell_Type = self.type;
            poVC.refer_price = self -> productModel.refer_price;
            [self.navigationController pushViewController:poVC animated:YES];
        }else{
            XMAlertView * alertView = [[XMAlertView alloc]initWithAlertViewWithMsg:@"您的账户余额不足"];
            [alertView show];
            SKWeakSelf;
            alertView.leftBlock = ^{
                XMRechargeViewController * poVC = [[XMRechargeViewController alloc]init];
                [weakSelf.navigationController pushViewController:poVC animated:YES];
            };
        }
    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;//商品简介 竞购成功者 商品参数  商品图片
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:{
            return 1;
        }
            break;
        case 1:{
            return [self.tipsArray count];
        }
            break;
        case 2:{
            return 1;
        }
            break;
        case 3:{
            return 1;
        }
        default:
            break;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:{
            return self.type == 5?60:130;
        }
            break;
        case 1:
        case 2:{
            return 45;
        }
            break;
        case 3:{
            return webCellHeight;
        }
        default:
            break;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:{//产品简介
            static NSString *CellIdentifier = @"ProductInfomationViewCell";
            ProductInfomationViewCell *cell = (ProductInfomationViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier ];
            if (cell == nil) {
                cell = [[ProductInfomationViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier type:self.type];
            }
            cell.theNewPrice.text = [NSString stringWithFormat:@"￥%@",productModel.the_new_price];
            cell.lowPrice.text = [NSString stringWithFormat:@"￥%@",productModel.bail];
            cell.addPrice.text = [NSString stringWithFormat:@"￥%@",productModel.range];
            switch (self.type) {
                case 1:{
                    if ([productModel.lost_begin_time integerValue] > 0) {//未开始
                    cell.timeLabel.textColor = [UIColor darkGrayColor];
                    cell.timeLabel.text = [NSString stringWithFormat:@"距开始：%02zd时%02zd分%02zd秒", [productModel.lost_begin_time integerValue]/3600, ([productModel.lost_begin_time integerValue]/60)%60, [productModel.lost_begin_time integerValue]%60];
                    }else{
                        cell.timeLabel.textColor = [UIColor darkGrayColor];
                        cell.timeLabel.text = @"竞拍未开始";
                    }
                }
                    break;
                case 2:
                {//
                    if ([productModel.lost_end_time integerValue] > 0) {//未开始
                        cell.timeLabel.textColor = [UIColor darkGrayColor];
                        cell.timeLabel.text = [NSString stringWithFormat:@"距结束：%02zd时%02zd分%02zd秒", [productModel.lost_end_time integerValue]/3600, ([productModel.lost_end_time integerValue]/60)%60, [productModel.lost_end_time integerValue]%60];
                    }else{
                        cell.timeLabel.textColor = [UIColor darkGrayColor];
                        cell.timeLabel.text = @"竞拍进行中";
                    }
                }
                    break;
                case 3:{
                    cell.timeLabel.textColor = [UIColor darkGrayColor];
                    cell.timeLabel.text = @"竞拍已结束";
                }
                    break;
                case 4:{
                    [cell.userHeadImg sd_setImageWithURL:[NSURL URLWithString:productModel.sell_log[@"head_url"]] placeholderImage:[UIImage imageNamed:@"DefaultHead"]];
                    cell.username.text = SafeString(productModel.sell_log[@"nickname"]);
                    cell.contentLab.text = [NSString stringWithFormat:@"出价%@，竞拍成功",SafeString(productModel.sell_log[@"price"])];
                    cell.timeLabel.textColor = [UIColor darkGrayColor];
                    cell.timeLabel.text = @"竞拍已结束";
                }
                    break;
                case 5:{
                    cell.timeLabel.textColor = [UIColor redColor];
                    cell.timeLabel.text = [NSString stringWithFormat:@"积分：%@+%@元",jifenModel.jifen,jifenModel.price];
                }
                    break;

                default:
                    break;
            }
            cell.productName.text = self.type == 5?jifenModel.name:productModel.title;
            return cell;
        }
            break;
        
        case 1:{//参数
            static NSString *CellIdentifier = @"ProductParmsTableViewCell";
            ProductParmsTableViewCell *cell = (ProductParmsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[ProductParmsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.parmName.text = self.tipsArray[indexPath.row];
            cell.parmContent.text = self.contentArray[indexPath.row];
            cell.lineView.hidden = indexPath.row == self.tipsArray.count - 1;//最后一个隐藏横线
            if (self.type != 5) {
                cell.accessoryType = (indexPath.row == 3 || indexPath.row == 4)?UITableViewCellAccessoryDisclosureIndicator:UITableViewCellAccessoryNone;
            }
            return cell;
        }
            break;
        case 2:{
            static NSString *CellIdentifier = @"ProductParmsTableViewCell";
            ProductParmsTableViewCell *cell = (ProductParmsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[ProductParmsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.parmName.text = @"商品详情";
            cell.lineView.hidden = YES;//最后一
            return cell;
        }
            break;
        case 3:{//
            static NSString *CellIdentifier = @"ProductImagesTableViewCell";
            ProductImagesTableViewCell *cell = (ProductImagesTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[ProductImagesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            //H5加载
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
             NSString *headStr = @"<head><style>img{width:100% !important}</style></head>";
            cell.contentString = self.type == 5?[NSString stringWithFormat:@"%@%@",headStr,SafeString(jifenModel.contents)]:[NSString stringWithFormat:@"%@%@",headStr,SafeString(productModel.contents)];
            cell.WebLoadFinish = ^(CGFloat cell_h) {
                
                if (self->webCellHeight != cell_h)
                {
                    self->webCellHeight = cell_h;
                    [tableView reloadData];
                }
            };
            
            
            return cell;
        }
            break;

        default:
            break;
    }
    static NSString *CellIdentifier = @"UITableViewCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    return cell;
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 && self.type != 5) {
        if (indexPath.row == 3) {//出价记录
            YXLPriceHistoryViewController * poVC = [[YXLPriceHistoryViewController alloc]init];
            poVC.sell_id = self.productId;
            poVC.sell_Type = self.type;
            poVC.refer_price = self -> productModel.refer_price;

            [self.navigationController pushViewController:poVC animated:YES];
        }else if (indexPath.row == 4) {//竞购规则
            [self LoadHtmlDataByType:7];
        }
    }
}

-(void)LoadHtmlDataByType:(NSInteger )type{
    [SVProgressHUD show];
    [YQNetworking postWithUrl:@"Index/getNotice" refreshRequest:YES cache:NO params:@{@"type":@(type)} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [SVProgressHUD dismiss];
        XMJSWebViewController * webVC = [[XMJSWebViewController alloc]init];
        webVC.type = WebType_H5_content;
        webVC.titleString = SafeString(@"竞拍规则");
        webVC.fileUrl = SafeString(response[@"data"][0][@"contents"]);
        [self.navigationController pushViewController:webVC animated:YES];
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, section == 1?10:CGFLOAT_MIN)];
    view.backgroundColor = BackColor;
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return (section == 1 || section == 2)?10:CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
#pragma -makr Setter
-(UITableView *)tableList{
    if (!_tableList) {
        _tableList = [[UITableView alloc]initWithFrame:CGRectMake(0, IS_IPhoneX_All?88:64, SCREEN_WIDTH, SCREENH_HEIGHT  - SKBottomSafe_Height  - (self.fromOrder?0:50) - (IS_IPhoneX_All?88:64))  style:UITableViewStylePlain];
        _tableList.dataSource = self;
        _tableList.delegate = self;
        _tableList.showsVerticalScrollIndicator = NO;
        _tableList.showsHorizontalScrollIndicator = NO;
        _tableList.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return  _tableList;
}
-(UIButton *)toSaleSquare{
    if (!_toSaleSquare) {
        _toSaleSquare = [UIButton buttonWithType:UIButtonTypeCustom];
        _toSaleSquare.frame = CGRectMake(0, SCREENH_HEIGHT - 50 - SKBottomSafe_Height, SCREEN_WIDTH, 50);
        _toSaleSquare.backgroundColor = SKColorWithHex(0x7ab801);
        if (self.type == 1 || self.type == 2) {
            [_toSaleSquare setTitle:@"我要竞拍" forState:UIControlStateNormal];
        }else if(self.type == 3 || self.type == 4){
            [_toSaleSquare setTitle:@"查看会场" forState:UIControlStateNormal];
        }else if(self.type == 5){
            [_toSaleSquare setTitle:@"我要购买" forState:UIControlStateNormal];
        }
        [_toSaleSquare addTarget:self action:@selector(toSaleSquarePress) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toSaleSquare;
}
-(SDCycleScrollView *)bannerView{
    if (!_bannerView) {
        _bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * bannerRadio) shouldInfiniteLoop:YES imageNamesGroup:@[]];
    }
    return _bannerView;
}
-(UIImageView*)zhanWeiImageView
{
    if (_zhanWeiImageView == nil) {
        
        _zhanWeiImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * (57/75.0))];
        _zhanWeiImageView.image = SKIMAGE_NAMED(@"bannerPlacehoder");
        
    }
    
    return _zhanWeiImageView;
}
-(NSMutableArray *)tipsArray{
    if (!_tipsArray) {
        if (self.type == 5) {
            _tipsArray = [NSMutableArray arrayWithArray:@[@"供应商",@"数量",@"规格/材质",@"市场价"]];

        }else{
            _tipsArray = [NSMutableArray arrayWithArray:@[@"开始时间",@"结束时间",@"市场价",@"出价记录",@"竞拍规则"]];
        }
    }
    return _tipsArray;
}
-(NSMutableArray *)contentArray
{
    if (!_contentArray) {
        if (self.type == 5) {
            _contentArray = [NSMutableArray arrayWithArray:@[@"供应商",@"0",@"无",@"￥0.0"]];

        }else{
            _contentArray = [NSMutableArray arrayWithArray:@[@"00:00",@"00:00",@"￥00.0",@"",@""]];
        }
    }
    return _contentArray;
}
- (NSTimer *)timer {
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCutDown) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}
#pragma mark - 倒计时
- (void)timerCutDown{
    /// 判断是否需要倒计时 -- 可能有的cell不需要倒计时,根据真实需求来进行判断
    if (!productCell) {
        productCell = (ProductInfomationViewCell *)[_tableList cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    }
    
    if (productModel.status == 1 && [productModel.lost_begin_time integerValue] > 0) {//未开始
        NSInteger countDown = [productModel.lost_begin_time integerValue] - 1;
        productModel.lost_begin_time = [NSString stringWithFormat:@"%ld",[productModel.lost_begin_time integerValue] - 1];
        /// 当倒计时到了进行回调
        if (countDown <= 0) {
            NSInteger endDown =  [productModel.lost_end_time integerValue];//直接变成距结束
            productModel.status = 2;
            productCell.timeLabel.text = [NSString stringWithFormat:@"距结束：%02zd时%02zd分%02zd秒", endDown/3600, (endDown/60)%60, endDown%60];
            return;
        }
        /// 重新赋值
        productCell.timeLabel.text = [NSString stringWithFormat:@"距开始：%02zd时%02zd分%02zd秒", countDown/3600, (countDown/60)%60, countDown%60];
    }else if (productModel.status == 2  && [productModel.lost_end_time integerValue] > 0) {//距结束
        NSInteger countDown =  [productModel.lost_end_time integerValue] - 1;
        productModel.lost_end_time = [NSString stringWithFormat:@"%ld",[productModel.lost_end_time integerValue] - 1];
        /// 当倒计时到了进行回调
        if (countDown <= 0) {
            productCell.timeLabel.text = @"已结束";
            productModel.status = 3;
            [self.timer invalidate];
            self.timer = nil;
            return;
        }
        /// 重新赋值
         productCell.timeLabel.text = [NSString stringWithFormat:@"距结束：%02zd时%02zd分%02zd秒", countDown/3600, (countDown/60)%60, countDown%60];
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [SVProgressHUD dismiss];


}
@end
